<template>
  <div class="chat-content">
    <div class="content-data" v-loading="topicLoading" loading-tip="数据发送中">
      <ChatCommunication
        ref="chatCommunicationRef"
        :messageList="dataObj.messageList"
        :selectTopic="dataObj.selectTopic"
        @addMessage="addMessage"
        @msgHandle="setSelectTopic"
        @sendMessage="sendMessage"
      ></ChatCommunication>
      <ChatSend
        ref="chatSendRef"
        @sendMessage="sendMessage"
        @stopBack="stopBack"
      ></ChatSend>
    </div>
  </div>
</template>

<script setup name="ChatContent">
import ChatCommunication from "./components/ChatCommunication.vue";
import ChatSend from "./components/ChatSend.vue";
import { message } from "ant-design-vue";
import { qaChat, controllerAbort } from "./chat";
// import IconFont from "@/components/IconFont/index.vue";
import { useChatData } from "./hooks/useChatData";
import { useRouter } from "vue-router";
// import { useGoPage } from "@/hooks/useGoPage";
// import { userStore } from "@/store/modules/user";
import { cloneDeep } from "lodash-es";
import { buildUUID } from "@/utils/uuid";
const { currentRoute, replace } = useRouter();

import { addHisChat, cancelChat } from "@/api";
// const { sessionExists, addHisChat, cancelChat } = api;

const emit = defineEmits(["updatePaiNum"]);

const {
  selectSessionId,
  setSessionId,
  refreshSession,
  setRefreshSession,
  sendLoading,
  setSendLoading,
  initChatData,
} = useChatData();

// const goPage = useGoPage();
// const userModule = userStore();

const chatCommunicationRef = ref(null);
const chatSendRef = ref(null);
const topicLoading = ref(false);
const dataObj = reactive({
  messageList: [],
  selectTopic: {},
});

const selectArticle = reactive({
  bindArticleId: "",
  bindArticleTitle: "",
});

// const tokenValue = computed(() => userModule.token);

const setSelectTopic = (params) => {
  setSessionId("");
  // getArticle("");
  dataObj.messageList = [];
  if (chatCommunicationRef.value) {
    chatCommunicationRef.value.initInfinite();
  }
  dataObj.selectTopic = {
    contextMsg: params.contextMsg,
    questionMsg: params.questionMsg,
    answerMsg: params.answerMsg,
    bindNo: params.bindNo,
  };
};

onMounted(async () => {
  // 判断存储session是否有效
  // if (selectSessionId.value) {
  //   let res = await sessionExists({
  //     sessionId: selectSessionId.value,
  //   });
  //   if (!res.result) {
  //     setSessionId("");
  //     getMessageList("");
  //   } else {
  //     // await getArticle(selectSessionId.value);
  //   }
  // }
  // if (userModule.loginModal == "2") {
  //   loginEvent();
  // }
});

const addMessage = (list) => {
  dataObj.messageList.unshift(...list);
};
const getMessageList = async (sessionId) => {
  dataObj.messageList = [];
  dataObj.selectTopic = {};
  if (chatCommunicationRef.value) {
    chatCommunicationRef.value.initInfinite();
  }
  if (chatSendRef.value) {
    chatSendRef.value.textareaFocus();
  }
  // getArticle(sessionId);
};

// 滚动到底部
const scrollHandle = () => {
  if (chatCommunicationRef.value) {
    chatCommunicationRef.value.scrollHandle();
  }
};
// 更新pai豆
const updatePaiNum = () => {
  emit("updatePaiNum");
};
// 停止响应
const stopBack = async () => {
  const messageObj = dataObj.messageList[dataObj.messageList.length - 1];
  // if (messageObj.chatNo) {
  //   await cancelChat({
  //     chatNo: messageObj.chatNo,
  //   });
  // }
  messageObj.responseStatus = "";
  messageObj.contextMsg = removeEscapedChars(messageObj.contextMsg);
  messageObj.extField = JSON.stringify({ stopSend: "1" });
  console.log('messageObj--',messageObj);
  
  setSendLoading(false)
  controllerAbort()
};
const removeEscapedChars = (str) => {
  if (str.endsWith("\\\\")) {
    str = str.slice(0, -2);
  }
  if (str.endsWith("\\")) {
    str = str.slice(0, -1);
  }
  return str;
};
// 读取sse流
const readStream = async (reader) => {
  let partialLine = "";

  const decoder = new TextDecoder("utf-8");

  while (true) {
    // eslint-disable-next-line no-await-in-loop
    const { value, done } = await reader.read();
    if (done) break;

    const decodedText = decoder.decode(value, { stream: true });

    const chunk = partialLine + decodedText;
    const newLines = chunk.split(/\r?\n/);

    partialLine = newLines.pop() ?? "";

    for (const line of newLines) {
      console.log(line);
      if (line.length === 0) continue; // 忽略空消息
      if (line.startsWith(":")) continue; // 忽略SSE的注释
      if (line.startsWith("retry:")) continue; // 忽略重试
      // if (line === "data:[DONE]") return // 结束

      if (line === "id:[DONE]" || line === "data:[DONE]" || line === "data:[stop]" || line === "data: [DONE]") {
        // TODO 回调函数形式
        const messageObj = dataObj.messageList[dataObj.messageList.length - 1];
        // if (!messageObj.contextMsg) {
        //   messageObj.contextMsg = 'GPU繁忙啦，请稍候再试'
        // }
        messageObj.responseStatus = "";
        if (line === "data:[stop]") {
          if (!messageObj.contextMsg) {
            dataObj.messageList.pop();
          } else {
            messageObj.contextMsg = removeEscapedChars(messageObj.contextMsg);
            messageObj.extField = JSON.stringify({ stopSend: "1" });
          }
        }
        // 保存bot消息
        // await saveMsg(messageObj)
        setSendLoading(false);
        // updatePaiNum();
        scrollHandle();
        return;
      }
      // console.log(line)
      // data:{"role":"assistant","content":"作为","name":null}
       let line_json = JSON.parse(line.substring(5)); // start with "data: "
      // let line_json = line.substring(5) // start with "data: "
      console.log('line_json--',line_json);
      
      if (line_json.source && line_json.source.length) {
        appendLastMessageContent({ source: line_json.source }, "source");
      } else if (line_json.recommend && line_json.recommend !== 'null' && line_json.recommend.length) {
        appendLastMessageContent({ recommend: line_json.recommend }, "recommend");
      } else if (line_json.rspCode) {
        appendLastMessageContent(
          { ...line_json, content: line_json.contextMsg, rspCode: line_json.rspCode },
          "rspCode"
        );
      } else {
        // console.log(line_json)
         const content = line_json.contextMsg;
         
     //   const content = line_json;
        appendLastMessageContent({ content }, "content");
      }
    }
  }
};
// 追加到最新一条消息调整
const appendLastMessageContent = (item, type) => {
  if (type === "source") {
    dataObj.messageList[dataObj.messageList.length - 1].source = item.source;
  } else if (type === "recommend") {
    dataObj.messageList[dataObj.messageList.length - 1].recommend = item.recommend;
  } else if (type === "rspCode" && item.rspCode === "410003") {
    dataObj.messageList[dataObj.messageList.length - 1].contextMsg += item.content;
    dataObj.messageList[dataObj.messageList.length - 1].insufficientQuantity = "1";
  } else if (type === "rspCode" && item.rspCode === "91111") {
    // if (!dataObj.messageList[dataObj.messageList.length - 1].sessionId) {
    //   dataObj.messageList[dataObj.messageList.length - 1].sessionId = item.sessionId;
    //   setSessionId(item.sessionId);
    //   setRefreshSession(true);
    // }
    dataObj.messageList[dataObj.messageList.length - 1].chatNo = item.chatNo;
    dataObj.messageList[dataObj.messageList.length - 1].msgId = item.msgId;
  } else {
    if (item.content !== null) {
      dataObj.messageList[dataObj.messageList.length - 1].contextMsg += item.content;
    }
  }
  console.log('dataObj--',dataObj);
  
  scrollHandle();
};
// 发送数据
const sendMessage = async (messageObj) => {
  // debugger;
  // if (!dataObj.messageList[dataObj.messageList.length - 1].sessionId) {
  //   const uuid = buildUUID();
  //   dataObj.messageList[dataObj.messageList.length - 1].sessionId = uuid;
  //   setSessionId(uuid);
  //   setRefreshSession(true);
  // }

  let messageObjCopy = cloneDeep(messageObj);
  try {
    messageObj.sessionId = selectSessionId.value;

    // if (dataObj.selectTopic.contextMsg) {
    //   topicLoading.value = true;
    //   let hisRes = await addHisChat({
    //     ...messageObj,
    //     direction: "A",
    //     ...dataObj.selectTopic,
    //   });
    //   topicLoading.value = false;
    //   if (hisRes.result) {
    //     messageObj.sessionId = hisRes.result.sessionId;
    //     setSessionId(messageObj.sessionId);
    //     // getArticle(messageObj.sessionId);
    //     setRefreshSession(true);
    //   }
    // }

    dataObj.messageList.push(messageObj); // 用户 O
    if (!dataObj.messageList[dataObj.messageList.length - 1].sessionId) {
      const uuid = buildUUID();
      dataObj.messageList[dataObj.messageList.length - 1].sessionId = uuid;
      setSessionId(uuid);
      setRefreshSession(true);
    }
    setSendLoading(true);
    scrollHandle();



    // BOT empty message
    const emptyMessageObj = {
      ...messageObj,
      contextMsg: "",
      direction: "A",
      responseStatus: "waitLoading",
    };
    console.log('emptyMessageObj---',emptyMessageObj);
    dataObj.messageList.push(emptyMessageObj);
    const result = await qaChat(messageObj);
    const { body, status } = result;
    console.log("body----", body);
    scrollHandle();
    if (body) {
      const reader = body.getReader();
      await readStream(reader);
    }

    // setTimeout(async()=>{
    //   if (body) {
    //   const reader = body.getReader();
    //   await readStream(reader);
    // }
    // },1000)
  } catch (error) {
    console.log('error--',error);
    
    topicLoading.value = false;
    const messageObj = dataObj.messageList[dataObj.messageList.length - 1];
    if (messageObj && messageObj.responseStatus === "waitLoading") {
      if (messageObj.contextMsg) {
        messageObj.responseStatus = "";
        messageObj.recommend = [];
        // await saveMsg(messageObj)
        // updatePaiNum();
      } else {
        dataObj.messageList.pop();
      }
    }
    setSendLoading(false);
    if (error.code === "420009") {
      // userModule.setVisitorsMsg({
      //   type: "chatSend",
      //   value: messageObjCopy,
      //   extra: {
      //     bindArticleId: selectArticle.bindArticleId,
      //     bindArticleTitle: selectArticle.bindArticleTitle,
      //   },
      // });
      // userModule.setLoginModel("1");
    }
  }
};

defineExpose({
  getMessageList,
});
</script>

<style lang="scss" scoped>
.chat-content {
  height: 100%;
  flex: 1;
  background: #f3f4f8;
  display: flex;
  justify-content: center;
  .content-article {
    width: 100%;
    height: 40px;
    background: #edf3fe;
    display: flex;
    justify-content: center;
    .article-box {
      width: 100%;
      min-width: 600px;
      max-width: 964px;
      padding: 0 84px;
      display: flex;
      align-items: center;
      cursor: pointer;
      .box-link {
        color: #3267ff;
        font-size: 14px;
      }
      .box-article {
        font-weight: 600;
        font-size: 14px;
        color: #192236;
        line-height: 16px;
        margin-left: 8px;
        margin-right: 24px;
      }
      .box-view {
        font-weight: 600;
        font-size: 14px;
        line-height: 16px;
      }
    }
  }
  .content-data {
    width: 100%;
    // min-width: 800px;
    // max-width: 964px;
    padding-bottom: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
  }
}
</style>
